"""
the current monitor with ina219 chip for static out port.
"""
import uasyncio as asyncio
from machine import Pin, I2C
from IIC_INA219 import INA219
class Current_Monitor:
    # 分路电阻值，单位为欧姆（强制）
    SHUNT_OHMS = 0.1
    # 以安培为单位的最大预期电流（可选）
    MAX_EXPECTED_AMPS = 3.2

    def __init__(self, iic_scl, iic_sda, current_callback=None):
        print("-" * 36)
        print("init Current Monitor...")
        self.i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=400000)
        self.current_callback = current_callback
        self.current_monitors = {}
        self._init_current_monitor()
        print("Current Monitor inited:", self.current_monitors.keys())
        asyncio.create_task(self.loop_check_current())
        print("-" * 36)

    def _init_current_monitor(self):
        addrs = self.i2c.scan()
        print("find iic addrs:", addrs)
        for addr in addrs:
            ina = INA219(self.SHUNT_OHMS, self.i2c, address=addr)
            ina.configure(ina.RANGE_16V)
            if addr == 64:  # +3.3V current monitor
                self.current_monitors["monitor_+3V3"] = ina
            if addr == 65:  # +3.3V current monitor
                self.current_monitors["monitor_-5V"] = ina
            if addr == 68:  # +5V current monitor
                self.current_monitors["monitor_+5V"] = ina
            if addr == 69:  # +5V current monitor
                self.current_monitors["monitor_+12V"] = ina
            if addr == 70:  # +5V current monitor
                self.current_monitors["monitor_-12V"] = ina

    async def loop_check_current(self):
        while True:
            try:
                data = {}
                for k, v in self.current_monitors.items():
                    data[k] = v.current()
                if self.current_callback:
                    self.current_callback(data)
            except Exception as e:
                print("Current Monitor loop check current error:", e)
            await asyncio.sleep(1)

